<?php
if(isset($_GET['file'])) {
	$content = FileLastLines($_GET['file'], $_GET['lines']);
}

/**
 * 取文件最后$n行
 * @param string $filename 文件路径
 * @param int $n 最后几行
 * @return mixed false表示有错误，成功则返回字符串
 */
function FileLastLines($filename,$n){
  if(!$fp=fopen($filename,'r')){
    echo "打开文件失败，请检查文件路径是否正确，路径和文件名不要包含中文";
    return false;
  }
  $pos=-2;
  $eof="";
  $str="";
  while($n>0){
    while($eof!="\n"){
      if(!fseek($fp,$pos,SEEK_END)){
        $eof=fgetc($fp);
        $pos--;
      }else{
        break;
      }
    }
    $str.=fgets($fp);
    $eof="";
    $n--;
  }
  return $str;
}
//echo nl2br(FileLastLines('sss.txt',4));
//echo (FileLastLines('tail.php',4));

function searchDir($path,&$files,$ext=null){

  if(is_dir($path)){

    $opendir = opendir($path);

    while ($file = readdir($opendir)){
      if($file != '.' && $file != '..'){
        searchDir($path.'/'.$file, $files, $ext);
      }
    }
    closedir($opendir);
  }
  if(!is_dir($path)){
//	  echo $ext;
//	  echo strlen($ext);
//	  echo substr($path, -(strlen($ext)));
	  if(!$ext || ($ext && substr($path, -(strlen($ext))) == $ext))
	    $files[] = $path;
  }
}

//得到目录名
function getDir($dir){
  $files = array();
  searchDir($dir, $files);
  return $files;
}
//$filenames = getDir('.');
//
//foreach ($filenames as $value){
////  echo $value.'<br/>';
//  echo $value."\n";
//} 

function getLogs($dir){
	$files = [];
	searchDir($dir, $files, '.log');
	return $files;
}

//print_r(getLogs('.'));
$logFiles = getLogs('.');
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP日志查询系统</title>
</head>
<body>

<form>
	<select name="file">
		<?php foreach($logFiles as $k => $logf):?>
		<option <?=@$_GET['file']==$logf?'selected':''?>><?=$logf?></option>
		<?php endforeach;?>
	</select>
	<select name="lines">
		<option <?=@$_GET['lines']==100?'selected':''?>>100</option>
		<option <?=@$_GET['lines']==10?'selected':''?>>10</option>
		<option <?=@$_GET['lines']==50?'selected':''?>>50</option>
		<option <?=@$_GET['lines']==300?'selected':''?>>300</option>
		<option <?=@$_GET['lines']==500?'selected':''?>>500</option>
	</select>
	<button type="submit">查询</button>
</form>

<hr>
<div>
	<?=nl2br($content)?>
</div>

</body>
</html>